package com.example.demo.controller;

import com.example.demo.entity.MembReceipt;
import com.example.demo.mapper.MembReceiptMapper;
import com.example.demo.utils.PagingResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 会员收货地址控制器
 */
@CrossOrigin
@RestController
@RequestMapping("/memb-receipt")
public class MembReceiptController {

    @Autowired
    private MembReceiptMapper membReceiptMapper;

    /**
     * 分页查询会员收货地址
     * @param limit 每页数量
     * @param offset 偏移量
     * @param field 查询字段
     * @param code 查询值
     * @return 分页结果
     */
    @GetMapping("/list")
    public PagingResult<MembReceipt> list(
            @RequestParam(required = false, name = "limit", defaultValue = "10") int limit,
            @RequestParam(required = false, name = "offset", defaultValue = "0") int offset,
            @RequestParam(required = false, name = "field", defaultValue = "") String field,
            @RequestParam(required = false, name = "code", defaultValue = "") String code
    ) {
        List<MembReceipt> list;
        int total;
        
        if (field != null && code != null && !code.trim().isEmpty()) {
            list = membReceiptMapper.selectByPageAndSearch(offset, limit, field, code);
            total = membReceiptMapper.countBySearch(field, code);
        } else {
            list = membReceiptMapper.selectByPage(offset, limit);
            total = membReceiptMapper.count();
        }
        
        return new PagingResult<>(list, total);
    }

    /**
     * 根据ID查询会员收货地址
     * @param id 收货地址ID
     * @return 会员收货地址
     */
    @GetMapping("/{id}")
    public MembReceipt getById(@PathVariable Integer id) {
        return membReceiptMapper.selectById(id);
    }

    /**
     * 根据会员ID查询收货地址列表
     * @param membId 会员ID
     * @return 收货地址列表
     */
    @GetMapping("/member/{membId}")
    public List<MembReceipt> getByMembId(@PathVariable Integer membId) {
        return membReceiptMapper.selectByMembId(membId);
    }

    /**
     * 新增会员收货地址
     * @param membReceipt 会员收货地址
     * @return 影响行数
     */
    @PostMapping
    public int add(@RequestBody MembReceipt membReceipt) {
        return membReceiptMapper.insert(membReceipt);
    }

    /**
     * 更新会员收货地址
     * @param membReceipt 会员收货地址
     * @return 影响行数
     */
    @PutMapping
    public int update(@RequestBody MembReceipt membReceipt) {
        return membReceiptMapper.update(membReceipt);
    }

    /**
     * 删除会员收货地址
     * @param id 收货地址ID
     * @return 影响行数
     */
    @DeleteMapping("/{id}")
    public int delete(@PathVariable Integer id) {
        return membReceiptMapper.deleteById(id);
    }

    /**
     * 批量删除会员收货地址
     * @param ids 收货地址ID列表
     * @return 影响行数
     */
    @DeleteMapping("/batch")
    public int deleteBatch(@RequestBody List<Integer> ids) {
        return membReceiptMapper.deleteByIds(ids);
    }
}